package org.numb.concurrency.chapter02;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketThread implements Runnable {

    @Override
    public void run() {
        // 线程运行中
        System.out.println("运行");
        try (ServerSocket server = new ServerSocket(8080)) {
            // 调用accept(), 线程阻塞
            System.out.println("阻塞");
            server.setSoTimeout(5 * 1000);
            Socket accept = server.accept();
            BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
            System.out.println(reader.readLine());
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("结束");
    }

    public static void main(String[] args) throws InterruptedException {
        // 新建线程
        System.out.println("新建");
        Thread thread = new Thread(new SocketThread());
        // 调用start()后，线程就绪
        System.out.println("就绪");
        thread.start();
    }
}
